import { View, Text, Image } from '@tarojs/components'
import { useLoad, useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import './index.scss'
import CategoryTabs from '../../components/common/CategoryGrid/CategoryTabs'
import FloatLoginBar from '../../components/common/FloatLoginBar'
import Taro from '@tarojs/taro'

export default function Category() {
  // 当前激活的选项卡
  const [activeTab, setActiveTab] = useState<'category' | 'service'>('category')
  
  // 当前选中的主分类ID
  const [activeMainId, setActiveMainId] = useState(1)

  // 当前选中的子分类ID
  const [activeSubId, setActiveSubId] = useState(1)

  useLoad(() => {
    console.log('Category page loaded.')
  })

  // 页面显示时检查是否有目标分类信息
  useDidShow(() => {
    const targetCategory = Taro.getStorageSync('targetCategory')
    if (targetCategory) {
      console.log('检测到目标分类信息:', targetCategory)
      if (targetCategory.categoryId) {
        console.log('设置activeMainId为:', targetCategory.categoryId)
        setActiveMainId(targetCategory.categoryId)
      }
      if (targetCategory.tab) {
        console.log('设置activeTab为:', targetCategory.tab)
        setActiveTab(targetCategory.tab as 'category' | 'service')
      }
      // 清除存储的信息，避免重复处理
      Taro.removeStorageSync('targetCategory')
    }
  })

  // 分类数据
  const categories = [
    { id: 1, name: '骨灰容器', icon: 'funeral-urn' },
    { id: 2, name: '寿衣', icon: 'burial-clothes' },
    { id: 3, name: '殡葬花艺', icon: 'funeral-flowers' },
    { id: 4, name: '纸扎祭品', icon: 'memorial-items' }
  ]

  // 服务数据
  const services = [
    { id: 1, name: '悼念定制', icon: 'memorial' },
    { id: 2, name: '法事服务', icon: 'legal' },
    { id: 3, name: '遗体接运', icon: 'transport' },
    { id: 4, name: '祭扫服务', icon: 'memorial' }
  ]

  // 子类数据
  const subCategories = {
    // 分类下的子类
    category: [
      { id: 1, name: '推荐', parentId: 0 },
      { id: 2, name: '木质骨灰盒', parentId: 1 },
      { id: 3, name: '玉石骨灰盒', parentId: 1 },
      { id: 4, name: '金属骨灰盒', parentId: 1 },
      { id: 5, name: '生态葬容器', parentId: 1 },
      // 寿衣子分类
      { id: 6, name: '唐装寿衣', parentId: 2 },
      { id: 7, name: '中山装寿衣', parentId: 2 },
      { id: 8, name: '西装寿衣', parentId: 2 },
      { id: 9, name: '旗袍寿衣', parentId: 2 },
      { id: 10, name: '陪葬内衣鞋袜', parentId: 2 },
      // 殡葬花艺子分类
      { id: 11, name: '纸质花圈', parentId: 3 },
      { id: 12, name: '鲜花花圈', parentId: 3 },
      { id: 13, name: '心形遗体鲜花', parentId: 3 },
      { id: 14, name: '十字形遗体鲜花', parentId: 3 },
      { id: 15, name: '手持悼念花束', parentId: 3 },
      // 纸扎祭品子分类
      { id: 16, name: '房子模型', parentId: 4 },
      { id: 17, name: '车马模型', parentId: 4 },
      { id: 18, name: '手机', parentId: 4 },
      { id: 19, name: '电脑模型', parentId: 4 },
    ],
    // 服务下的子类
    service: [
      { id: 1, name: '推荐', parentId: 0 },
      { id: 2, name: '个性定制服务', parentId: 1 },
      { id: 3, name: '传统法事', parentId: 2 },
      { id: 4, name: '遗体接运服务', parentId: 3 },
      { id: 5, name: '祭扫陪同', parentId: 4 },
      { id: 6, name: '墓地鲜花', parentId: 4 },
    ]
  }

  // 服务子分类
  const subServices = {
    1: [ // 悼念定制
      { id: 1, name: '推荐' },
      { id: 2, name: '悼词' },
      { id: 3, name: '挽联' },
      { id: 4, name: '纪念视频' }
    ],
    2: [ // 法事服务
      { id: 1, name: '推荐' },
      { id: 2, name: '灵堂布晋' },
      { id: 3, name: '追悼会主持' },
      { id: 4, name: '电子讣告' },
      { id: 5, name: '佛教超度' },
      { id: 6, name: '基督教追思礼拜' }
    ],
    3: [ // 遗体处理
      { id: 1, name: '推荐' },
      { id: 2, name: '遗体接运' },
      { id: 3, name: '遗体冷藏' },
      { id: 4, name: '遗体整容' }
    ],
    4: [ // 祭扫服务
      { id: 1, name: '推荐' },
      { id: 2, name: '直播扫墓' },
      { id: 3, name: '录像扫墓' },
      { id: 4, name: '节日祭品代烧' }
    ]
  }


  // 获取当前选项卡下的主分类列表
  const getCurrentMainItems = () => {
    return activeTab === 'category' ? categories : services
  }

  // 获取当前选中主分类对应的子分类列表
  const getCurrentSubItems = () => {
    if (activeTab === 'category') {
      return subCategories[activeTab].filter(
        item => item.parentId === 0 || item.parentId === activeMainId
      )
    } else {
      return subServices[activeMainId] || []
    }
  }

  return (
    <View className='category-container'>
      {/* 头部搜索区域 */}
      <View className='search-bar'>
        <View className='search-input'>
          <Text className='search-placeholder'>搜索商品</Text>
        </View>
        <View className='category-tabs'>
          <Text 
            className={`tab ${activeTab === 'category' ? 'active' : ''}`}
            onClick={() => {
              setActiveTab('category');
              setActiveMainId(categories[0].id);
              setActiveSubId(1);
            }}
          >
            分类专区
          </Text>
          <Text 
            className={`tab ${activeTab === 'service' ? 'active' : ''}`}
            onClick={() => {
              setActiveTab('service');
              setActiveMainId(services[0].id);
              setActiveSubId(1);
            }}
          >
            服务
          </Text>
        </View>
      </View>

      {/* 主分类横向区域 */}
      <View className='main-category-bar'>
        <CategoryTabs
          categories={getCurrentMainItems().map(item => {
            // 根据图标名称返回对应的素材图路径
            const iconMap = {
              'funeral-urn': '/assets/images/icons/funeral-urn.jpg',
              'burial-clothes': '/assets/images/icons/burial-clothes.jpg',
              'funeral-flowers': '/assets/images/icons/funeral-flowers.png',
              'memorial-items': '/assets/images/icons/memorial-items.jpg',
              'memorial': '/assets/images/icons/memorial.png',
              'legal': '/assets/images/icons/legal.png',
              'transport': '/assets/images/icons/transport.png'
            }
            return {
              id: item.id,
              name: item.name,
              icon: iconMap[item.icon] || `/assets/images/icons/${item.icon}.png`
            }
          })}
          activeId={activeMainId}
          onChange={id => { setActiveMainId(id); setActiveSubId(1); }}
        />
      </View>

      {/* 内容区：左侧子分类，右侧内容 */}
      <View className='content-area'>
        {/* 左侧子分类竖排 */}
        <View className='sub-category-bar'>
          {getCurrentSubItems().map(subItem => (
            <View
              key={subItem.id}
              className={`sub-category-item ${subItem.id === activeSubId ? 'active' : ''}`}
              onClick={() => setActiveSubId(subItem.id)}
            >
              <Text className='sub-category-text'>{subItem.name}</Text>
            </View>
          ))}
        </View>
        {/* 右侧内容区 */}
        <View className='main-content'>
          <View className='product-list'>
            {[
              {
                id: 1,
                name: '木质骨灰盒A',
                price: '¥800',
                tag: '热销',
                img: '/assets/images/icons/funeral-urn.jpg',
                desc: '优质木材，工艺精湛'
              },
              {
                id: 2,
                name: '玉石骨灰盒B',
                price: '¥1500',
                tag: '新品',
                img: '/assets/images/icons/funeral-urn.png',
                desc: '天然玉石，典雅大气'
              },
              {
                id: 3,
                name: '寿衣C',
                price: '¥1200',
                tag: '推荐',
                img: '/assets/images/icons/burial-clothes.jpg',
                desc: '高档寿衣，舒适美观'
              },
              {
                id: 4,
                name: '纪念用品D',
                price: '¥980',
                tag: '纪念',
                img: '/assets/images/icons/memorial-items.jpg',
                desc: '多样纪念，精美实用'
              }
            ].map(product => (
              <View className='product-card' key={product.id} onClick={() => Taro.navigateTo({ url: '/pages/product-detail/index' })}>
                <Image className='product-img' src={product.img} mode='aspectFill' />
                <View className='product-info'>
                  <Text className='product-tag-wrap'>
                    <Text className='product-tag-inner'>{product.tag}</Text>
                  </Text>
                  <View className='product-title-row'>
                    <Text className='product-title'>{product.name}</Text>
                  </View>
                  <Text className='product-desc'>{product.desc}</Text>
                  <Text className='product-price'>{product.price}</Text>
                </View>
              </View>
            ))}
          </View>
        </View>
      </View>
      <FloatLoginBar />
    </View>
  )
} 